package com.stop.activity.fragment;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.stop.R;
import com.stop.controller.StopController;

public class SalaDescriptionActivity extends Fragment{
	
	private View view = null;
	
	private JSONObject salaResumed;
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = (ScrollView) inflater.inflate(R.layout.activity_info_sala_fragment_description, container, false);
		
		try{
			salaResumed = new JSONObject(this.getArguments().getString("sala"));
			
			new AtualizarDescription().execute();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		return view;
	}
	
	
	class AtualizarDescription extends AsyncTask<Void, Void, Void> {

		private JSONObject sala = null;
		
		protected Void doInBackground(Void... params) {
			
			try {
				JSONObject response = StopController.getInstancia().entrarSala(salaResumed.getString("uid"), "desc");
				
				if(!response.getBoolean("error")){
					this.sala = response.getJSONObject("sala");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return null;
		}
		
		protected void onPostExecute(Void result) {
			if(this.sala != null){
				try{
					
					TextView nomeSala = (TextView) view.findViewById(R.id.txtDescNomeSala);
					nomeSala.setText(sala.getString("nome"));
					
					TextView jogadores = (TextView) view.findViewById(R.id.txtDescJogadores);
					jogadores.setText(sala.getString("qntJogadores")+"/"+sala.getString("vagas") + " Jogadores");
					
					TextView rodadas = (TextView) view.findViewById(R.id.txtDescRodadas);
					rodadas.setText(sala.getString("rodadaAtual")+"/"+sala.getString("rodadas") + " Partidas");
					
					TextView temas = (TextView) view.findViewById(R.id.txtDescTemas);
					
					JSONArray array = sala.getJSONArray("temas");
					String temasString = "";
					for (int i = 0; i < array.length()-1; i++) {
						temasString+=array.getString(i);
						temasString+=", ";
					}
					temasString+=array.getString(array.length()-1);
					
					temas.setText(temasString);
					
					if(view.getVisibility() == view.INVISIBLE){
						view.setVisibility(view.VISIBLE);
					}
					
				}catch(Exception e){
					e.printStackTrace();
				}
			}			
		}
	}

}
